let timer;
let currentIndex = 0;
let names = [];

document.addEventListener('DOMContentLoaded', () => {
    const startBtn = document.getElementById('startBtn');
    const stopBtn = document.getElementById('stopBtn');
    const nameList = document.getElementById('nameList');
    const displayArea = document.getElementById('displayArea');

    startBtn.addEventListener('click', () => {
        names = nameList.value.split('\n').filter(name => name.trim() !== '');
        if (names.length < 2) {
            alert('请至少输入两个学生姓名！');
            return;
        }
        
        startBtn.disabled = true;
        stopBtn.disabled = false;
        displayArea.classList.add('rolling');
        
        timer = setInterval(() => {
            currentIndex = Math.floor(Math.random() * names.length);
            displayArea.textContent = names[currentIndex];
        }, 50);
    });

    stopBtn.addEventListener('click', () => {
        clearInterval(timer);
        startBtn.disabled = false;
        stopBtn.disabled = true;
        displayArea.classList.remove('rolling');
        displayArea.classList.add('highlight');
        
        // 移除已选中的名字
        const selectedName = names[currentIndex];
        names.splice(currentIndex, 1);
        nameList.value = names.join('\n');
        
        setTimeout(() => {
            displayArea.classList.remove('highlight');
            alert(`选中学生：${selectedName}`);
        }, 500);
    });

    nameList.addEventListener('input', () => {
        startBtn.disabled = nameList.value.trim().split('\n').filter(n => n).length < 2;
    });
});
